/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.dwusoft.net.service.plugins  
 */
package com.dwusoft.ius.impl;

import java.util.HashMap;
import java.util.Map;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SpringContextLoader;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.exception.BusinessException;
import com.apache.tools.StrUtil;
import com.dwusoft.ius.CustomMethodFactory;
import com.dwusoft.ius.FelToolsUtil;
import com.dwusoft.ius.IusSqlTools;
import com.dwusoft.ius.plugin.CustomMethodPlugin;
import com.dwusoft.ius.plugin.IusSqlPorxyPlugin;

/**
 * description:  IUS事务处理插件
 * @author Administrator 创建时间：2016-12-7  
 * @Copyright(c)2014:东吴（北京）软件技术有限公司
 */
public class PlateTransactionPluginImpl implements PluginConnector {

	private IDao iusPubDao;
	private IusSqlPorxyPlugin iusSqlPorxyPlugin;

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.apache.api.manager.PluginConnector#execute(com.apache.api.vo.ParamsVo)  
	 */
	public Object execute(ParamsVo param) throws Exception {
		String key = String.valueOf(param.getParams("sqlKeyId"));
		MethodParam params = new MethodParam(key, "", "", "com.dwusoft.net.trans.TransPublic");
		ResultEntity entity = new ResultEntity();
		entity.setResult("true");
		try {
			String resultType = String.valueOf(param.getParams("resultType"));
			if ("processSql".equalsIgnoreCase(resultType)) {
				processSql(entity, params, param);
			} else if ("objInfo".equals(resultType)) {
				selectObjInfo(entity, params, param);
			}
		} catch (BusinessException e) {
			param.setParams("businessException", e.getMessage());
			throw new BusinessException(e.getMessage());
		}
		return entity;
	}

	private void processSql(ResultEntity entity, MethodParam params, ParamsVo paramVo) {
		String execSql = "";
		String cateNo = String.valueOf(paramVo.getParams("cateNo"));
		if (Validator.isNotNull(cateNo)) {
			FelToolsUtil.getInstance().evl(paramVo);
		}
		exeCustomPlugin(paramVo, "befor");
		if (Validator.isNotNull(String.valueOf(paramVo.getParams("businessSuccese")))) {
			entity.setResult("T");
			entity.setMessage(String.valueOf(paramVo.getParams("businessSuccese")));
			return;
		}
		execSql = IusSqlTools.getInstance().cteageNativeSql(paramVo);
		String pluginSql = String.valueOf(paramVo.getParams("customPlugin_exeSql"));//插件中生成的sql
		if (Validator.isNotNull(pluginSql)) {
			execSql += pluginSql;
		}
		if (Validator.isNotNull(execSql)) {
			params.setKey("ByDymicSql");
			params.setParams("execSql", execSql);
			iusPubDao.edit(params);
			//String result = (String) params.getParamsByKey("result");
			//	if ("T".equals(result)) {
			entity.setEntity(paramVo.getParams("resultIds"));
			entity.setResult("T");
			entity.setMessage("操作成功");
			//} else {
			//	entity.setMessage("执行失败");
			//}
			//exeCustomPluginForAfter(paramVo, "after");
		} else {
			entity.setMessage("缺少方法执行参数");
		}
	}

	private void selectObjInfo(ResultEntity entity, MethodParam params, ParamsVo paramVo) {
		String execSql = IusSqlTools.getInstance().dymicNativeSql(paramVo);
		if (Validator.isNotNull(execSql)) {
			String modelTypes = String.valueOf(paramVo.getParams("modelTypes"));
			if (modelTypes.startsWith("s_")) {
				params.setKey("ByObjInfo");
				params.setParams("dyncSql", execSql);
				Object obj = null;
				Map<String, Object> map = paramVo.getParams();
				params.setResultCache(false);
				String rows = String.valueOf(paramVo.getParams("rows"));
				if (Validator.isNull(rows)) {
					//params.setParams(map);
					String val = String.valueOf(paramVo.getParams("resultObjType"));
					if ("obj".equals(val)) {
						obj = iusPubDao.selectSingle(params);
					} else {
						obj = iusPubDao.select(params);
					}
				} else {
					params.setPageIndex(Integer.valueOf(StrUtil.doNull(String.valueOf(paramVo.getParams("page")), "1")));
					//params.setParams(map);
					params.setPageSize(Integer.valueOf(rows));
					obj = iusPubDao.pageSelect(params);
				}
				if (!Validator.isEmpty(obj)) {
					entity.setEntity(obj);
					entity.setResult("查询成功");
				} else {
					entity.setMessage("执行失败");
				}
			} else {
				params.setKey("ByDymicSql");
				params.setParams("execSql", execSql);
				iusPubDao.edit(params);
				//String result = (String) params.getParamsByKey("result");
				//if ("T".equals(result)) {
				entity.setEntity(paramVo.getParams("resultIds"));
				entity.setResult("T");
				//} else {
				//	entity.setMessage("执行失败");
				//}
			}
		} else {
			entity.setMessage("缺少方法执行参数");
		}
	}

	private void exeCustomPluginForAfter(ParamsVo vo, String type) {
		Map<String, Object> map = new HashMap<String, Object>();
		String keys = String.valueOf(vo.getParams("sqlKeyId"));
		if (Validator.isNotNull(keys)) {
			String beforMethodKey = String.valueOf(vo.getParams("afterMethodKey"));
			if (Validator.isNull(beforMethodKey)) {
				return;
			} else {
				vo.setMethodKey("afterMethodKey");
				vo.setParams("afterMethodKey", "");
			}
			map = (Map) getPlugin().doInvoke(vo);
			vo.setParams("sqlKeyId", "");
		} else {
			if ("after".equals(type)) {
				String beforMethodKey = String.valueOf(vo.getParams("afterMethodKey"));
				if (Validator.isNull(beforMethodKey))
					return;
				vo.setMethodKey("afterMethodKey");
				CustomMethodPlugin after = CustomMethodFactory.getInstance().getPluginByKey(beforMethodKey);
				if (!Validator.isEmpty(after)) {
					map = (Map) after.afterInvoke(vo.getParams());
				}
				vo.setParams("afterMethodKey", "");
			}
		}
		if (!Validator.isEmpty(map) && !map.isEmpty()) {
			for (String key : map.keySet()) {
				vo.setParams(key, map.get(key));
			}
		}
	}

	private void exeCustomPlugin(ParamsVo vo, String type) {
		Map<String, Object> map = new HashMap<String, Object>();
		String keys = String.valueOf(vo.getParams("sqlKeyId"));
		if (Validator.isNotNull(keys)) {
			String beforMethodKey = String.valueOf(vo.getParams("beforMethodKey"));
			if (Validator.isNull(beforMethodKey)) {
				return;
			} else {
				vo.setMethodKey("beforMethodKey");
				vo.setParams("beforMethodKey", "");
			}
			map = (Map) getPlugin().doInvoke(vo);
			vo.setParams("sqlKeyId", "");
		} else {
			if ("befor".equals(type)) {
				String beforMethodKey = String.valueOf(vo.getParams("beforMethodKey"));
				if (Validator.isNull(beforMethodKey))
					return;
				vo.setMethodKey("beforMethodKey");
				CustomMethodPlugin befor = CustomMethodFactory.getInstance().getPluginByKey(beforMethodKey);
				if (!Validator.isEmpty(befor)) {
					map = (Map) befor.beforeInvoke(vo.getParams());
					vo.setParams("beforMethodKey", "");
				}
			}
		}
		if (!Validator.isEmpty(map)) {
			for (String key : map.keySet()) {
				vo.setParams(key, map.get(key));
			}
		}
	}

	public void setIusPubDao(IDao iusPubDao) {
		this.iusPubDao = iusPubDao;
	}

	private IusSqlPorxyPlugin getPlugin() {
		if (null == iusSqlPorxyPlugin) {
			iusSqlPorxyPlugin = (IusSqlPorxyPlugin) SpringContextLoader.getBean("iusSqlPorxyPlugin");
		}
		return iusSqlPorxyPlugin;
	}

	//	public void setNetSqlPorxyPlugin(NetSqlPorxyPlugin netSqlPorxyPlugin) {
	//		this.netSqlPorxyPlugin = netSqlPorxyPlugin;
	//	}

}
